/*
 * @FileName: [OperatorController.java]
 * 
 * @Package controller
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO Technology Limited Company ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 42 $ $LastChangedDate: 2013-10-12 10:19:36 +0800 (星期六, 12 十月 2013) $ $LastChangedBy: wanggc $
 * 
 * @category bcinfo-upp
 * 
 * @version 1.1
 * 
 * @author $Author: wanggc $
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

package com.bcinfo.iccard.admin.ac.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bcinfo.iccard.admin.common.Constants;
import com.bcinfo.iccard.admin.common.ModuleEnum;
import com.bcinfo.iccard.admin.controller.AbstractController;
import com.bcinfo.upp.ac.model.Operator;
import com.bcinfo.upp.ac.model.OrgUsers;
import com.bcinfo.upp.ac.model.Organization;
import com.bcinfo.upp.ac.model.Role;
import com.bcinfo.upp.ac.service.OperatorService;
import com.bcinfo.upp.ac.service.OrganizationService;
import com.bcinfo.upp.ac.service.PermissionService;
import com.bcinfo.upp.ac.service.RoleService;
import com.bcinfo.upp.ac.util.AcConstant;
import com.bcinfo.upp.exception.InvalidParametersException;
import com.bcinfo.upp.exception.UppDataBaseException;
import com.bcinfo.upp.exception.UppException;
import com.bcinfo.upp.util.PaginationList;

/**
 * 用户用户控制器controller <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 包含以下功能 <br/>
 * 新增管理员 <br/>
 * 修改管理员 <br/>
 * 删除管理员 <br/>
 * 查询管理员 <br/>
 * 启用/禁用管理员 <br/>
 * For Examples <br/>
 * 
 * <PRE>
 *      /user/${actionName}
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/ac/user")
public class OperatorController extends AbstractController
{
    @Autowired()
    private OperatorService     _operatorService;

    @Autowired()
    private RoleService         _roleService;

    @Autowired()
    private PermissionService   _permissionService;

    @Autowired
    private OrganizationService _organizationService;

    /**
     * 转到operator列表页面 <br/>
     * <p>
     * Description: 转到operator列表页面 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-12-下午2:56:22<br/>
     * <p>
     * 
     * @return
     * 
     */
    @RequestMapping("/toListView")
    public ModelAndView toListView()
    {
        String keywords = request.getParameter("keywords") == null ? "" : request.getParameter("keywords");
        request.setAttribute("keywords", keywords);
        return new ModelAndView("ac/user/user_list");
    }

    /**
     * 查询operator列表 <br/>
     * <p>
     * Description: 查询operator列表 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-12-下午2:57:52<br/>
     * <p>
     * 
     * @return
     * 
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(String keywords)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        PaginationList<Operator> list = null;

        try
        {
            list = _operatorService.listAll(keywords, getPage(), getPageSize());
            if (list != null)
            {
                map.put("rows", list.getRecords());
                map.put("total", list.getTotalRecord());
            }
        }
        catch (UppException e)
        {
            map.put("total", 0);
            handleException(e);
        }
        catch (Exception e)
        {
            map.put("total", 0);
            handleException(e);
        }

        return map;
    }

    /**
     * 创建operator信息 <br/>
     * <p>
     * Description: 创建operator信息 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-12-下午2:58:32<br/>
     * <p>
     * 
     * @param request
     * @param response
     * @return
     * 
     */
    @RequestMapping("/add")
    @ResponseBody
    public Map<String, String> add(HttpServletRequest request, Operator operator)
    {
        if (!this.hasPermission(ModuleEnum.Operator.add))// 没有权限
        {
            _log.error("权限不足");
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        }
        Map<String, String> map = null;

        try
        {
            operator.setLoginPassword(DigestUtils.md5Hex(Constants.DEFAULT_PASSWORD));
            operator.setCreateTime(new Timestamp(System.currentTimeMillis()));
            operator.setStatus(AcConstant.VALID);

            Operator operatorOwner = getCurrentOperator();
            operator.setOwner(operatorOwner.getOperatorId());

            Long operatorId = _operatorService.add(operator);

            // 页面上勾选的角色
            String roleIdsStr = request.getParameter("selectedRoleIds");
            if (StringUtils.isNotBlank(roleIdsStr))
            {
                String ids[] = StringUtils.split(roleIdsStr, ",");
                long[] roleIds = new long[ids.length];
                for (int i = 0; i < ids.length; i++)
                {
                    roleIds[i] = Long.valueOf(ids[i]);
                }
                _roleService.assignRole(operatorId, roleIds);
            }

            // 页面上勾选的组织
            String checkedOrgIds = request.getParameter("checkedOrgIds");
            if (StringUtils.isNotBlank(checkedOrgIds))
            {
                String ids[] = StringUtils.split(checkedOrgIds, ",");
                long[] orgIds = new long[ids.length];
                for (int i = 0; i < ids.length; i++)
                {
                    orgIds[i] = Long.valueOf(ids[i]);
                }
                _operatorService.assignOrg(operatorId, orgIds);
            }
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Operator.add, "operatorId=" + operator.getOperatorId() + "|desc=新增用户信息成功");

        }
        catch (UppException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Operator.add, "新增用户信息失败");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Operator.add, "新增用户信息失败");
        }
        return map;
    }

    /**
     * 转到新增页面 <br/>
     * <p>
     * Description: 转到新增页面 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-17-上午11:30:01<br/>
     * <p>
     * 
     * @return ModelAndView
     * 
     */
    @RequestMapping("/toAddView")
    public ModelAndView toAddView()
    {
        Operator operatorOwner = getCurrentOperator();
        ModelAndView mv = new ModelAndView("ac/user/user_add");
        // 可分配角色列表
        List<Role> listRoles = null;
        try
        {
            listRoles = _roleService.findByOwner(operatorOwner.getOperatorId());
        }
        catch (UppDataBaseException e)
        {
            handleException(e);
            return mv.addObject("message", getErrorMessage("UppDataBaseException"));
        }

        return mv.addObject("listRoles", listRoles);
    }

    /**
     * 设置operator状态<br/>
     * <p>
     * Description: operator启用、禁用功能 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-12-下午2:59:27<br/>
     * <p>
     * 
     * @param request
     * @return
     * 
     */
    @RequestMapping("/setStatus")
    @ResponseBody
    public Map<String, String> setStatus(Operator operator)
    {
        if (!this.hasPermission(ModuleEnum.Operator.setStatus))// 没有权限
        {
            _log.error("权限不足");
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        }
        Map<String, String> map = null;
        try
        {
            _operatorService.setStatus(operator.getOperatorId(), operator.getStatus());

            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);

            if (operator.getStatus() == AcConstant.VALID)
            {
                addLog(ModuleEnum.Operator.setStatus, "启用用户成功");
            }
            else
            {
                addLog(ModuleEnum.Operator.setStatus, "禁用用户成功");
            }

            return map;

        }
        catch (UppException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            if (operator.getStatus() == AcConstant.VALID)
            {
                addLog(ModuleEnum.Operator.setStatus, "启用用户失败");
            }
            else
            {
                addLog(ModuleEnum.Operator.setStatus, "禁用用户失败");
            }
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            if (operator.getStatus() == AcConstant.VALID)
            {
                addLog(ModuleEnum.Operator.setStatus, "启用用户失败");
            }
            else
            {
                addLog(ModuleEnum.Operator.setStatus, "禁用用户失败");
            }
        }
        return map;
    }

    /**
     * 删除用户 <br/>
     * <p>
     * Description: 删除用户 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-18-下午2:09:07<br/>
     * <p>
     * 
     * @param operator
     * @return
     * 
     */
    @RequestMapping("/remove")
    @ResponseBody
    public Map<String, String> remove(Operator operator)
    {
        if (!this.hasPermission(ModuleEnum.Operator.remove))// 没有权限
        {
            _log.error("权限不足");
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        }
        Map<String, String> map = null;
        if (operator == null || operator.getOperatorId() <= 0)
        {
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                    "InvalidParameterException", null);
        }

        try
        {
            _operatorService.delete(operator.getOperatorId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Operator.remove, "operatorId=" + operator.getOperatorId() + "|desc=删除用户成功");
        }
        catch (UppException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Operator.remove, "删除用户失败");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Operator.remove, "删除用户失败");
        }
        return map;
    }

    /**
     * 编辑管理员<br/>
     * <p>
     * Description: 编辑管理员 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-18-下午3:18:32<br/>
     * <p>
     * 
     * @param operator
     * @return
     * 
     */
    @RequestMapping("/toEditView")
    public ModelAndView toEditView(Operator operator)
    {
        Operator operatorOwner = getCurrentOperator();
        ModelAndView modelAndView = new ModelAndView("ac/user/user_edit");

        // 可分配角色列表
        List<Role> listRoles = null;
        try
        {
            listRoles = _roleService.findByOwner(operatorOwner.getOperatorId());
            _log.info("可分配角色：" + listRoles);
        }
        catch (UppDataBaseException e)
        {
            handleException(e);
            return modelAndView.addObject("message", getErrorMessage("UppDataBaseException"));
        }

        // 已分配的角色列表
        List<Role> listAssignedRoles = null;
        try
        {
            listAssignedRoles = _permissionService.listAssignedRoles(operator.getOperatorId());
        }
        catch (UppDataBaseException e)
        {
            handleException(e);
            return modelAndView.addObject("message", getErrorMessage("UppDataBaseException"));
        }
        catch (InvalidParametersException e)
        {
            handleException(e);
            return modelAndView.addObject("message", getErrorMessage("InvalidParametersException"));
        }

        // 已分配的组织start
        List<OrgUsers> listUserOrgs = null;
        String orgIdStrs = "";
        try
        {
            listUserOrgs = _organizationService.findOrgUsersByUserId(operator.getOperatorId());
            if (listUserOrgs != null && !listUserOrgs.isEmpty())
            {
                for (OrgUsers ou : listUserOrgs)
                {
                    orgIdStrs += ou.getOrgId() + ",";
                }
            }
            _log.info("已分配的组织listUserOrgs：" + listUserOrgs);
            _log.info("已分配的组织Ids：" + orgIdStrs);
        }
        catch (InvalidParametersException e)
        {
            handleException(e);
            return modelAndView.addObject("message", getErrorMessage("InvalidParametersException"));
        }
        catch (UppDataBaseException e)
        {
            handleException(e);
            return modelAndView.addObject("message", getErrorMessage("UppDataBaseException"));
        }
        // 已分配的组织end

        Operator _operator = null;
        try
        {
            _operator = this._operatorService.findById(operator.getOperatorId());
        }
        catch (UppDataBaseException e)
        {
            handleException(e);
            return modelAndView.addObject("message", getErrorMessage("UppDataBaseException"));
        }

        request.setAttribute("orgIdStrs", orgIdStrs);
        request.setAttribute("listRoles", listRoles);
        request.setAttribute("listAssignedRoles", listAssignedRoles);
        return modelAndView.addObject("operator", _operator);
    }

    /**
     * 更新用户 <br/>
     * <p>
     * Description: 更新用户 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-18-下午3:33:03<br/>
     * <p>
     * 
     * @param operator
     * @return
     * 
     */
    @RequestMapping("/update")
    @ResponseBody
    public Map<String, String> update(Operator operator)
    {
        if (!this.hasPermission(ModuleEnum.Operator.update))// 没有权限
        {
            _log.error("权限不足");
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        }
        Map<String, String> map = null;

        _log.error("operator:" + operator);
        if (operator == null || operator.getOperatorId() <= 0)
        {
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                    "InvalidParameterException", null);
        }
        try
        {
            operator.setLastModifiedTime(new Timestamp(System.currentTimeMillis()));
            _operatorService.update(operator);

            // 页面上勾选的角色
            String roleIdsStr = request.getParameter("selectedRoleIds");
            if (StringUtils.isNotBlank(roleIdsStr))
            {
                String ids[] = StringUtils.split(roleIdsStr, ",");
                long[] roleIds = new long[ids.length];
                for (int i = 0; i < ids.length; i++)
                {
                    roleIds[i] = Long.valueOf(ids[i]);
                }
                _roleService.assignRole(operator.getOperatorId(), roleIds);
            }

            // 页面上勾选的组织
            String checkedOrgIds = request.getParameter("checkedOrgIds");
            if (StringUtils.isNotBlank(checkedOrgIds))
            {
                String ids[] = StringUtils.split(checkedOrgIds, ",");
                long[] orgIds = new long[ids.length];
                for (int i = 0; i < ids.length; i++)
                {
                    orgIds[i] = Long.valueOf(ids[i]);
                }
                _operatorService.assignOrg(operator.getOperatorId(), orgIds);
            }
            else
            {
                _operatorService.assignOrg(operator.getOperatorId(), new long[0]);
            }

            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Operator.update, "更新用户信息成功");

        }
        catch (UppException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Operator.update, "更新用户信息失败");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Operator.update, "更新用户信息失败");
        }

        return map;
    }

    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @return
     * 
     * @see com.bcinfo.upp.admin.controller.AdminController#getMouduleCode()
     */
    public String getMouduleCode()
    {
        return ModuleEnum.Operator.moduleName.value;
    }

    /**
     * 
     * 一句话描述 <br/>
     * <p>
     * Description: TODO(详细描述) <br/>
     * <p>
     * Author: Administrator<br/>
     * <p>
     * Date: 2013-4-28-上午11:42:36<br/>
     * <p>
     * 
     * @return
     * 
     */
    @RequestMapping("/list_tree")
    @ResponseBody
    public List<Map<String, String>> list_tree()
    {
        String id = request.getParameter("id");
        String flag = request.getParameter("flag");
        String orgIdStrs = request.getParameter("orgIdStrs");
        _log.error("flag:" + flag);
        _log.error("orgIdStrs:" + orgIdStrs);
        if (StringUtils.isBlank(id))
        {
            id = "0";
        }
        List<Organization> list = null;
        try
        {
            list = _organizationService.listSubOrg(new Long(id));
            addLog(ModuleEnum.Org.view, "查询组织列表成功");
        }
        catch (UppException e)
        {
            handleException(e);
            addLog(ModuleEnum.Org.view, "查询组织列表失败；" + e.getMessage() + "异常");
        }
        catch (Exception e)
        {
            handleException(e);
            addLog(ModuleEnum.Org.view, "查询组织列表失败；" + e.getMessage() + "异常");
        }

        // 以下操作是把返回的接口List<Organization>数据转换成List<Map<String,String>>，因为在ZTree框架中，只认识id，pid,name,isParent
        List<Map<String, String>> backList = new ArrayList<Map<String, String>>();

        if (null != list && !list.isEmpty())
        {
            Iterator<Organization> it = list.iterator();
            Organization org = null;
            while (it.hasNext())
            {
                org = it.next();
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", String.valueOf(org.getOrgId()));
                map.put("pid", String.valueOf(org.getParentOrgId()));
                map.put("name", String.valueOf(org.getOrgName()));
                map.put("isParent", org.getIsTrunk());

                if ("edit".equals(flag) && StringUtils.isNotBlank(orgIdStrs))
                {
                    String ids[] = StringUtils.split(orgIdStrs, ",");
                    long[] orgIds = new long[ids.length];
                    for (int i = 0; i < ids.length; i++)
                    {
                        orgIds[i] = Long.valueOf(ids[i]);
                        if (org.getOrgId() == orgIds[i])
                        {
                            map.put("checked", "true");
                            map.put("open", "true");
                            break;
                        }
                    }
                }

                backList.add(map);
            }
        }
        return backList;
    }

    /**
     * 
     * 重置密码 <br/>
     * <p>
     * Description: TODO(详细描述) <br/>
     * <p>
     * Author: Administrator<br/>
     * <p>
     * Date: 2013-5-4-下午03:38:59<br/>
     * <p>
     * 
     * @param operator
     * @return
     * 
     */
    @RequestMapping("/resetPwd")
    @ResponseBody
    public Map<String, String> resetPwd(Operator operator)
    {
        if (!this.hasPermission(ModuleEnum.Operator.resetPwd))// 没有权限
        {
            _log.error("权限不足");
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        }
        Map<String, String> map = new HashMap<String, String>();
        try
        {
            _operatorService.modifyPassword(operator.getOperatorId(), DigestUtils.md5Hex(Constants.DEFAULT_PASSWORD));
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Operator.resetPwd, "operatorId=" + operator.getOperatorId() + "|desc=重置密码成功");
        }
        catch (UppException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Operator.resetPwd, "重置密码失败");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Operator.resetPwd, "重置密码失败");
        }

        return map;
    }

}